import { flux } from '../utils/flux'
import HttpUtil from '../utils/HttpUtil'
import useStore from "../store";


// 微信授权
let wxLoginCode

/**
 * 检测session是否过期
 * @param {Function} callback
 * { isExpired: false, errMsg: 'session_key 未过期，并且在本生命周期一直有效' }
 * { isExpired: true, errMsg: 'session_key 已经失效，需要重新执行登录流程' }
 */

export function checkSession() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: (res) => {
        console.log(res)
        resolve(true)
      },
      fail: (error) => {
        console.log(error)
        reject(error)
      }
    })
  })
}

/**
 * 微信授权手机授权获取手机号码
 * @param e
 * @returns {Promise<unknown>}
 */
export function getUserProfile(event) {
  wxLoginCode = null
  return checkSession()
    .then((res) => {
      return login(event, true)
    })
    .catch((err) => {
      return login(event, false)
    })
}

export function getMiniProgramLoginCode() {
  return new Promise((resolve, reject) => {
    wx.login({
      provider: 'weixin',
      success(loginRes) {
        wxLoginCode = loginRes.code
        resolve(wxLoginCode)
      },
      fail(res) {
        reject(res)
      }
    })
  })
}

export async function login(event, expires) {
  // checkSession 过期重新获取code
  if (!expires || !wxLoginCode) {
    await getMiniProgramLoginCode()
  }
  return HttpUtil.post(
      '/external/gameUser/v1/login',
      {
        encryptedData: event.encryptedData,
        appId: useStore().userStore.appId,
        code: wxLoginCode,
        nickName: event.userInfo.nickName,
        avatarUrl: event.userInfo.avatarUrl,
        gender: event.userInfo.gender
      }
    )
    .then((token) => {
      if (token) {
        // userStore.setToken(token)
        return getReaderInfo()
      }
      return flux.reject({})
    })
    .catch((error) => {
      // console.error('重新【token 获取失败】：', error)
      // 解密失败重新获取code
      wxLoginCode = null
      getMiniProgramLoginCode()
      return flux.reject(error)
    })
}

export function getReaderInfo() {
  return HttpUtil.get('/external/gameUser/v1/getUserInfo', {}).then((res) => {
    const { userStore } = useStore()
    userStore.setUserInfo(res)
    return res
  })
}

export function getUserScore() {
  return HttpUtil.get('/external/gameUser/v1/getUserScore', {}).then((score) => {
    const { userStore } = useStore()
    userStore.setUserInfo({maxScore: score})
  })
}

